public class NumIslands {
    // leetcode 岛屿数量
    // https://leetcode.cn/problems/number-of-islands/?envType=study-plan-v2&envId=top-100-liked
    boolean[][] vis;
    int[] dx = {0,0,-1,1};
    int[] dy = {-1,1,0,0};
    public int numIslands(char[][] grid) {
        int m = grid.length, n = grid[0].length;
        vis = new boolean[m][n];
        int ret = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!vis[i][j] && grid[i][j] == '1') {
                    dfs(grid, i, j);
                    ret++;
                }
            }
        }
        return ret;
    }

    private void dfs(char[][] grid, int x, int y) {
        vis[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int xx = x + dx[i], yy = y + dy[i];
            if (xx >= 0 && xx < grid.length && yy >= 0 && yy < grid[0].length && !vis[xx][yy] && grid[xx][yy] == '1') {
                dfs(grid, xx, yy);
            }
        }
    }
}
